package DD2;

class Window2 extends Thread {

	private static int money = 110;
	private static Object obj = new Object();

	public void run() {

		while (true) {
			// synchronized (obj){ // this is also can be used as the lock
			synchronized (Window2.class) {
				// Use the current class as the lock
				// synchronized (this){
				/**
				 * \\WRONG\\ because this is directly created by extends from Thread Class,we
				 * have created 3 object(ths object is not only ) So it can not use "this" as it
				 * lock
				 */

				if (money >= 20) {
					try {
						Thread.sleep(50);
					} catch (Exception e) {
						e.printStackTrace();
					}
					money -= 20;
					System.out.println(getName() + " take money,money left " + money);
				} else {
					break;
				}
			}
		}
	}
}

public class WindowTest2 {
	public static void main(String[] args) {
		Window2 t1 = new Window2();
		Window2 t2 = new Window2();
		Window2 t3 = new Window2();

		t1.setName("Person1");
		t2.setName("Person2");
		t3.setName("Person3");

		t1.start();
		t2.start();
		t3.start();

	}
}
